package ar.com.spsolutions.splilabrary.view.pages.book.gbook;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.spring.injection.annot.SpringBean;

import ar.com.spsolutions.splibrary.book.Book;
import ar.com.spsolutions.splibrary.services.google.books.GoogleBookService;

public class GoogleBookFinder implements Serializable {
    private static final long serialVersionUID = 6537456483269657061L;

    @SpringBean
    private GoogleBookService googleBookService;

    private List<Book> results;

    public void search(final String query) {
        setResults(getGoogleBookService().search(query).getItems());
    }

    public GoogleBookService getGoogleBookService() {
        return googleBookService;
    }

    public void setGoogleBookService(final GoogleBookService googleBookService) {
        this.googleBookService = googleBookService;
    }

    private void setResults(final List<Book> items) {
        results = items;
    }

    public List<Book> getResults() {
        return results;
    }

    public Iterator<? extends Book> iterator(final int first, final int count) {
        final int toIndex = (first + count) > getResults().size() ? first + count : getResults().size();
        return getResults().subList(first, toIndex).iterator();
    }

    public int size() {
        return getResults() == null ? 0 : getResults().size();
    }

    public void add(final Book book) {
        getGoogleBookService().add(book);
    }

}
